/**
 * Utils.m by Giraldo Rosales.
 * Visit www.liquidgear.net for documentation and updates.
 *
 * Copyright (c) 2009 Nitrogen Design, Inc. All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 **/

#import "Utils.h"
#import "CJSONSerializer.h"

@implementation Utils

- (void)jsCall:(UIWebView *)webView type:(NSString *)type data:(NSDictionary *)data directCall:(NSString *)directCall {
	
	NSString *jsCallback	= @"";
	
	if(data != nil) {
		NSString *jsData			= [[CJSONSerializer serializer] serializeObject:data];
		jsCallback	= [NSString stringWithFormat:@"lg.%@.callback(%@);", type, jsData];
	} else if(directCall != nil) {
		jsCallback	= [NSString stringWithFormat:@"%@;", directCall];
	} else {
		jsCallback	= [NSString stringWithFormat:@"lg.%@.callback();", type];
	}
	
	//Call javascript
	if(jsCallback == nil) {
		jsCallback = @"lg.nextCall();";
	} else {
		jsCallback = [NSString stringWithFormat:@"%@%@", jsCallback, @"lg.nextCall();"];
	}
	
	NSLog(@"Utils::jsCall: %@", jsCallback);
	
	[webView stringByEvaluatingJavaScriptFromString:jsCallback];
}

- (NSArray *)formatQuery:(NSURL *)url {
	if([url query] == nil) {
		return nil;
	}
	
	unsigned int size			= NSNotFound;
	NSString *query				= [NSString stringWithFormat:@"%@", [url query]];
	NSArray *args					= [query componentsSeparatedByString:@"&"];
	
	NSMutableArray *vars	= [NSMutableArray arrayWithCapacity:size];
	NSString *argSet;
	NSString *key;
	NSString *value;
	
	for(int g=0; g<[args count]; g++) {
		argSet	= [NSString stringWithFormat:@"%@", [args objectAtIndex:g]];
		key			= [[argSet componentsSeparatedByString:@"="] objectAtIndex:0];
		value		= [[argSet componentsSeparatedByString:@"="] objectAtIndex:1];
		
		key			= [key lowercaseString];
		value		= [self urldecode:value];
		
		[vars addObject:[NSArray arrayWithObjects:key,value,nil]];
	}
	
	return vars;
}

- (NSString *) urlencode: (NSString *) string {
	NSString *out = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	out = [out stringByReplacingOccurrencesOfString:@"'" withString:@"%27"];
	//out = [out stringByReplacingOccurrencesOfString:@" " withString:@"+"];
	return out;
}

- (NSString *) urldecode: (NSString *) url {
	NSString *out = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	//out = [out stringByReplacingOccurrencesOfString:@"%27" withString:@"'"];
	out = [out stringByReplacingOccurrencesOfString:@"\"\"" withString:@"\\\""];
	out = [out stringByReplacingOccurrencesOfString:@"+" withString:@" "];
	return out;
}

-(NSString *) dateInFormat:(NSString*)stringFormat date:(CFDateRef)date {
	//CFDateRef date = CFDateCreate(NULL, 123456);
	int formatStyle	= 0;
	
	if([stringFormat isEqualToString:@"short"]) {
			formatStyle = 1;
	}
	else if([stringFormat isEqualToString:@"medium"]) {
			formatStyle = 2;
	}
	
	else if([stringFormat isEqualToString:@"long"]) {
			formatStyle = 3;
	}
	
	else if([stringFormat isEqualToString:@"full"]) {
			formatStyle = 4;
	}
	
	CFLocaleRef currentLocale = CFLocaleCopyCurrent();
	CFDateFormatterRef dateFormatter = CFDateFormatterCreate(NULL, currentLocale, formatStyle, formatStyle);
	CFStringRef formattedString = CFDateFormatterCreateStringWithDate(NULL, dateFormatter, date);
	
	return [NSString stringWithFormat:@"%@", formattedString];
}

- (UIColor *) txtToColor:(NSString *)color {
	UIColor *txtColor;
	
	if([color isEqualToString:@"black"]) {
		txtColor	= [UIColor blackColor];
	}
	else if([color isEqualToString:@"darkGray"]) {
		txtColor	= [UIColor darkGrayColor];
	}
	else if([color isEqualToString:@"darkGray"]) {
		txtColor	= [UIColor darkGrayColor];
	}
	else if([color isEqualToString:@"lightGray"]) {
		txtColor	= [UIColor lightGrayColor];
	}
	else if([color isEqualToString:@"gray"]) {
		txtColor	= [UIColor grayColor];
	}
	else if([color isEqualToString:@"red"]) {
		txtColor	= [UIColor redColor];
	}
	else if([color isEqualToString:@"green"]) {
		txtColor	= [UIColor greenColor];
	}
	else if([color isEqualToString:@"blue"]) {
		txtColor	= [UIColor blueColor];
	}
	else if([color isEqualToString:@"cyan"]) {
		txtColor	= [UIColor cyanColor];
	}
	else if([color isEqualToString:@"yellow"]) {
		txtColor	= [UIColor yellowColor];
	}
	else if([color isEqualToString:@"magenta"]) {
		txtColor	= [UIColor magentaColor];
	}
	else if([color isEqualToString:@"orange"]) {
		txtColor	= [UIColor orangeColor];
	}
	else if([color isEqualToString:@"purple"]) {
		txtColor	= [UIColor purpleColor];
	}
	else if([color isEqualToString:@"brown"]) {
		txtColor	= [UIColor brownColor];
	}
	else if([color isEqualToString:@"clear"]) {
		txtColor	= [UIColor clearColor];
	} else {
		txtColor	= [UIColor whiteColor];
	}

	return txtColor;
}

- (UIImage *)tintImage:(UIImage *)baseImage color:(UIColor *)theColor {
	UIGraphicsBeginImageContext(baseImage.size);
	
	CGContextRef ctx = UIGraphicsGetCurrentContext();
	CGRect area = CGRectMake(0, 0, baseImage.size.width, baseImage.size.height);
	
	CGContextScaleCTM(ctx, 1, -1);
	CGContextTranslateCTM(ctx, 0, -area.size.height);
	CGContextSaveGState(ctx);
	CGContextClipToMask(ctx, area, baseImage.CGImage);
	
	[theColor set];
	
	CGContextFillRect(ctx, area);
	CGContextRestoreGState(ctx);
	CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
	CGContextDrawImage(ctx, area, baseImage.CGImage);
	
	UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
	
	UIGraphicsEndImageContext();
	
	return newImage;
}
@end
